﻿module Sustainalytics.GovernanceReports.Admin {

    import Common = Sustainalytics.Common;
    import CommonAdmin = Sustainalytics.Common.Admin;
    import Company = Sustainalytics.Company;

    export class GovernanceService implements IGovernanceService {

        private $q: ng.IQService;
        private $http: ng.IHttpService;
        private $location: ng.ILocationService;
        private staticObjectsAdmin: CommonAdmin.IStaticObjects;
        private notificationFactory: Common.INotificationFactory;
        private $upload: any;

        // Ctor.
        constructor(
            $q: ng.IQService,
            $http: ng.IHttpService,
            $location: ng.ILocationService,
            notificationFactory: Common.INotificationFactory,
            staticObjectsAdmin: CommonAdmin.IStaticObjects,
            $upload: any) {

            this.$q = $q;
            this.$http = $http;
            this.$location = $location;
            this.staticObjectsAdmin = staticObjectsAdmin;
            this.notificationFactory = notificationFactory;
            this.$upload = $upload;
        }

        // show error message for a given error code
        private showError(err) {
            var ctx = this;
            if (err && err['code'])
                ctx.notificationFactory.error('', ctx.staticObjectsAdmin.getMessageByInternalCode(err['code']));
        }

        // get filtered list of events 
        public getCompanyProfileAndInsights(companyId: string): ng.IPromise<GovernanceProfileDto> {
            var def = this.$q.defer();

            var url = '/governanceserv/api/v1/governanceadmin/' + companyId;

            var promise = this.$http.get(url);
            promise.success(data => {
                    def.resolve(data);
                })
                .error(err => {
                this.showError(err);
                def.reject();
            });
            return promise;
        }

        public getCompanyPdfProfile(companyId: string): ng.IPromise<GovernancePdfProfileMetadata[]> {
            var def = this.$q.defer<GovernancePdfProfileMetadata[]>();

            var url = '/governanceserv/api/v1/governanceadminpdfmetadata/' + companyId;

            var promise = this.$http.get(url);
            promise.success((data: GovernancePdfProfileMetadata[]) => { def.resolve(data); })
                .error(err => {
                    this.showError(err);
                    def.reject();
                });
            return def.promise;
        }

        public getCompanyById(id: string): ng.IHttpPromise<Company.CorporateDataExtendedDto> {

            var url: string = '/governanceserv/api/v1/company/' + id;

            var promise: ng.IHttpPromise<Company.CorporateDataExtendedDto> = this.$http.get(url);

            return promise;
        }

        private filesUrl(): string {
            var ctx = this;
            return ctx.$location.protocol() + "://" + ctx.$location.host() + ":" + ctx.$location.port() + "/governanceserv/api/v1/files/";
        }

        public fileUpload(file: File, id: string): ng.IPromise<{}> {
            var ctx = this;
            var def = ctx.$q.defer();

            var reader = new FileReader();
            reader.onload = (data) => {
                return ctx.$upload.http({
                    method: /*(id) ? "PUT" :*/ "POST",
                    url: ctx.filesUrl() /*+ ((id) ? id : "")*/,
                    headers: { 'Content-Disposition': 'attachment; filename=\"' + file.name + '\"', 'Content-Type': file.type },
                    data: reader.result
                })
                    .progress(evt => { console.log('percent: ' + (100.0 * evt.loaded / evt.total)); })
                    .success((data) => { def.resolve(data) })
                    .error((data) => {def.resolve(data)});
            };
            reader.readAsArrayBuffer(file);
            return def.promise;
        }
        //added by Ionut
        public fileUploadReportFile(file: File, companyId: string, governancePdfType: string, fileId: string): ng.IPromise<{}> {
            var ctx = this;
            var def = ctx.$q.defer();
            var fileUrlClientPlatform = ctx.$location.protocol() + "://" + ctx.$location.host() + ":" + ctx.$location.port() + "/governanceserv/api/v1/filesclientplatform";

            var reader = new FileReader();
            reader.onload = (data) => {
                return ctx.$upload.http({
                    method: /*(id) ? "PUT" :*/ "POST",
                    url: fileId == null ? fileUrlClientPlatform + "?companyId=" + companyId + "&governancePdfType=" + governancePdfType : fileUrlClientPlatform + "?companyId=" + companyId + "&governancePdfType=" + governancePdfType + "&fileId=" + fileId,
                    headers: { 'Content-Disposition': 'attachment; filename=\"' + file.name + '\"', 'Content-Type': file.type },
                    data: reader.result
                    })

                    .progress(evt => { console.log('percent: ' + (100.0 * evt.loaded / evt.total)); })
                    .success((data) => { def.resolve(data) })
                    .error((data) => { def.resolve(data) });
            };
            reader.readAsArrayBuffer(file);
            return def.promise;
        }

        public savePfdBusinessProfileMetadata(businessPdfProfile: GovernancePdfProfileMetadata) {
            var ctx = this;
            var url = '/governanceserv/api/v1/governanceadminpdfmetadata/';
            return ctx.$http.post<GovernanceProfileDto>(url, businessPdfProfile);
        }

        public saveProfile(dto: GovernanceProfileDto): ng.IHttpPromise<GovernanceProfileDto> {
            var ctx = this;
            var url = '/governanceserv/api/v1/governanceadmin/';
            return ctx.$http.post<GovernanceProfileDto>(url, dto);
        }

        public deleteProfile(companyId: string) {
            var ctx = this;
            var url = '/governanceserv/api/v1/governanceadmin/' + companyId;
            return ctx.$http.delete<GovernanceProfileDto>(url);
        }
        public deletePdfProfile(companyId: string, governancePdfType: GovernancePdfType) {
            var ctx = this;
            var url = '/governanceserv/api/v1/governanceadminpdfmetadata?companyId=' + companyId + "&governancePdfType=" + governancePdfType;
            return ctx.$http.delete<GovernanceProfileDto>(url);
        }
        public deleteInsight(companyId: string, fileId: string) {
            var ctx = this;
            var url = '/governanceserv/api/v1/governanceadminpdfmetadata?companyId=' + companyId + "&fileId=" + fileId;
            return ctx.$http.delete<GovernanceProfileDto>(url);
        }
        public saveInsight(insight: GovernanceInsightDto, companyName: string) {
            var ctx = this;
            insight.fileName = "Governance_Insight_" + companyName + "_" + insight.publicationDate.toString() + ".pdf";
            var url = '/governanceserv/api/v1/governanceadmin/';
            return ctx.$http.post<GovernanceProfileDto>(url, insight);
        }
    }

    // register service with News Angular module
    var mod = angular.module(governanceAdminReportsModuleName);
    
    mod.service('GovernanceService',
        ['$q', '$http', '$location', 'notificationFactory', 'staticObjectsAdmin', '$upload', GovernanceService]);
}  